package Tender_debryansk_ru;
use strict;
use warnings;
use Encode;
use Data::Dumper;
use WWW::Mechanize;

my $enabled = 0; # 1/0 - edit to enable/disable module
my $site_address = 'http://www.tender.debryansk.ru';


sub explore{
 my ( $self, $c ) = @_;
 return 1 if !$enabled;

 $c->debug_call("call explore conf=".$c->conf('user_agent')."\n");


 my $news = {
    site => $site_address,
    id => undef,
    url => undef,
    small_text => undef,
 };
 
 $c->debug_explain(" new WWW_Mechanize\n");
 my $m = WWW::Mechanize->new();
 my $url = "$site_address/jetspeed/portal/content/view/browser/general.jsp?show=tender";
 $m->get($url);
 $c->debug_explain("get content\n");
 my $co = $m->content;
 
 my $f = $c->{list_file} or die "file!";
 open FILE, ">$f" or die "Can't open $f: $!";
 $co = encode("utf8",$co);
 print FILE $co;
 close FILE;
 
 my $data_dir = $c->{data_dir} or die "dir!";
 my $links_file = "$data_dir/links.list";
 open FILE , ">$links_file" or die "Can't open $links_file: $!";
 my $l_regexp = '/jetspeed/portal/content/view/competition/general?id=\d+'; # url from link
 $l_regexp =~ s|([\?])|\\$1|g;
 $c->debug_explain("regexp = '$l_regexp'\n");
 my %l = $co =~ m|($l_regexp)\"\>(.+?)\<\/a\>|mg;
 $c->debug_explain("Founded links:", Dumper \%l , "It will Saved into file '$links_file'.");
 print FILE "$_ | $l{$_} \n" for keys %l;
 close FILE;
 
 my $inserted_cnt = 0;
 for my $url ( keys %l ){
    ( $news->{ id } ) = $url =~/id\=(\d+)/;
    $news->{ url } = "$url";
    $news->{ small_text } = "$l{$url}";
    
    # GO to url page and find customer :
    $m->get( $news->{ url } );
    $c->debug_explain("get page id=$news->{ id }\n");
    my $co = $m->content;
    $co = encode("utf8",$co);
#   Заказчик</td><td><a href="/jetspeed/portal/content/view/customer/general?id=100125687">ГСУСОССЗН "Клинцовский психоневрологический интернат"</a>  
    my ($cu) = $co =~ m|Заказчик\<\/td\>\<td\>\<a\s+href\=.+?>(.+?)</a>|m;
    $c->debug_explain("customer='$cu'\n");
    $news->{ customer } = $cu;
    
#  Предмет закупки</td><td>ремонт автомобильной  дороги по улице Горького города Карачева</td>:
    my ($pz) = $co =~ m|Предмет\s+закупки\<\/td\>\<td\>(.+?)</td>|m;
    $c->debug_explain("predmet zakupki=='$pz'\n");
    if ( length $pz > length $news->{ small_text } ){
	$news->{ small_text } .= " (".$pz.")";
	$c->debug_explain("add predmet zakupki to small_text\n");
    }
    #die Dumper "$pz";
    
    
#    # set_news() return 0-after error, 1-after insert news, 2-if news already exist and skipped, 3-if exist and updated
    my $set_rv = $c->set_news( $news, { update => 1 } ) 
	or $self->{error} = "Error while call set_news() (". __FILE__." line ".__LINE__."):\n ".$c->error(), return 0 ;
    $c->debug_explain(Dumper $news, "Set_news result: $set_rv");
    $inserted_cnt ++ if $set_rv == 1;
 }
 $c->set_stat( name_en=>"inserted_from_$site_address", name_ru=>"Последнее добавление с $site_address", val=>$inserted_cnt, 
    comment=>"(кол-во всех новых конкурсов)"  )  if $inserted_cnt;
 
 return 1;
}

sub new{
 my $package = shift;
 my $self = {
    site_address => $site_address,
    
 };
 return bless $self;
}

sub error{ shift->{error} }

sub enabled{ return $enabled }

1;
